package com.qianya.weishi_server.config.security;
import com.qianya.weishi_server.config.jwt.JwtProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.ObjectPostProcessor;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

import javax.annotation.Resource;


/**
 * Security配置
 *
 * @author LLL
 */
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Resource
    private JwtProperty jwtProperty;

    @Resource
    private UrlAccessDecisionManager urlAccessDecisionManager;
    @Resource
    private AuthenticationAccessDeniedHandler authenticationAccessDeniedHandler;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) {
        auth.authenticationProvider(new TokenAuthenticationProvider(new SecurityProviderManager(jwtProperty)));
    }

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        //禁用缓存
        httpSecurity.headers().cacheControl();
        httpSecurity.cors() //允许跨域
                .and()
                .csrf().disable()
                .authorizeRequests()
                .withObjectPostProcessor(new ObjectPostProcessor<FilterSecurityInterceptor>() {
                    @Override
                    public <O extends FilterSecurityInterceptor> O postProcess(O o) {
                        o.setAccessDecisionManager(urlAccessDecisionManager);
                        return o;
                    }
                })
                .antMatchers("/**").authenticated()
                .and()
                .formLogin().disable()
                .httpBasic().disable()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .securityContext()
                .and()
                .anonymous().disable()
                .exceptionHandling().accessDeniedHandler(authenticationAccessDeniedHandler)
                .and()
                .servletApi();

        AuthenticationManager authenticationManager = authenticationManager();
        TokenAuthenticationFilter authenticationFilter = new TokenAuthenticationFilter(authenticationManager);
        httpSecurity.addFilterBefore(authenticationFilter, UsernamePasswordAuthenticationFilter.class);
    }

    @Override
    public void configure(WebSecurity web) {
        /* 在这里配置security放行的请求 */
        // Druid监控平台
        web.ignoring().antMatchers("/druid/**");
        // 统一静态资源
//        web.ignoring().antMatchers("/**/*.gif", "/**/*.png", "/**/*.jpg", "/**/*.html", "/**/*.js", "/**/*.css", "/**/*.ico", "/webjars/**");
//        web.ignoring().antMatchers("/uploads/**");
        web.ignoring().antMatchers("/u/**");

        // swagger3
        web.ignoring().antMatchers("/swagger-ui/**", "/v3/api-docs");

        web.ignoring().mvcMatchers("/v2/api-docs", "/configuration/ui", "/configuration/security", "/swagger-resources/**");
        // 登陆
        web.ignoring().antMatchers("/user/login");

        web.ignoring().antMatchers("/appUser/login");
        web.ignoring().antMatchers("/appUser/loginByWX");
        web.ignoring().antMatchers("/appUser/sendSms");
        web.ignoring().antMatchers("/ws");
        web.ignoring().antMatchers("/open/**");

    }

    @Bean
    public CorsFilter corsFilter() {
        //1.添加CORS配置信息
        CorsConfiguration config = new CorsConfiguration();
        // 允许cookies跨域
        config.setAllowCredentials(true);
        // #允许向该服务器提交请求的URI，*表示全部允许，自定义可以添加多个，在SpringMVC中，如果设成*，会自动转成当前请求头中的Origin
        config.addAllowedOrigin("*");
        // #允许访问的头信息,*表示全部，可以添加多个
        config.addAllowedHeader("*");
        // 预检请求的缓存时间（秒），即在这个时间段里，对于相同的跨域请求不会再发送OPTIONS预检了
        config.setMaxAge(1800L);
        // 允许提交请求的方法，*表示全部允许，一般OPTIONS,GET,POST三个够了
        config.addAllowedMethod("*");

        //2.添加映射路径
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        //对所有接口都有效
        source.registerCorsConfiguration("/**", config);
        return new CorsFilter(source);
    }
}
